//
//  SongsViewController.swift
//  ShareMusic
//
//  Created by 胡岩 on 16/5/4.
//  Copyright © 2016年 胡岩. All rights reserved.
//

import UIKit
import MJRefresh

enum SongListsType {
    case Download
    case Collect
    case NetLoad
    case Rank
    case Search
}

class SongsViewController: SMBViewController, UITableViewDelegate, UITableViewDataSource, SMBTableViewDelegate, UISearchBarDelegate {
    var parameters:[String:AnyObject]?
    var lists:NSMutableArray = NSMutableArray.init(capacity: 0)
    var tableView:SMBTableView?
    var page:Int = 1
    var tag_id:NSNumber?
    var activityView:UIActivityIndicatorView?
    var type:SongListsType?
    var rankUrl:String = URLs.getSingerIdBySongsId
    var searchBar:UISearchBar?
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        if self.parameters != nil {
            self.network()
        } else if self.type == SongListsType.Rank {
            self.getRankList()
        } else if self.type == SongListsType.Search {
            self.initView()
        } else {
            self.getLocalData(type == SongListsType.Download ? true : false)
        }
    }
    
    func getLocalData(download:Bool) {
        if download == true {
            let db:Database = Database.init()
            let array:NSArray = db.select(DBType.Download)
            self.lists.addObjectsFromArray(array as [AnyObject])
        } else {
            let db:Database = Database.init()
            let array:NSArray = db.select(DBType.Collect)
            self.lists.addObjectsFromArray(array as [AnyObject])
        }
        if (self.tableView != nil) {
            self.tableView?.reloadData()
        } else {
            self.initView()
        }
    }
    
    func getRankList() {
        Network.networkGet(URLs.rankDetailsUrl.stringByAppendingString("\(tag_id!)")) { (json) in
            let array:NSArray = json["data"] as! NSArray
            for dic in array {
                let song:songModel = songModel.init(dic: dic as? [String : AnyObject])
                self.rankUrl = self.rankUrl.stringByAppendingString("\(song.song_id!)")
                self.rankUrl = self.rankUrl.stringByAppendingString("%2C")
            }
            self.network()
        }
    }
    
    func network() {
        var url:String?
        if type == SongListsType.Rank {
            url = self.rankUrl
        } else if self.type == SongListsType.Search {
            url = URLs.searchSongsUrl.stringByAppendingString((self.searchBar?.text)! + "&size=100").stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
        } else {
            url = URLs.searchListUrl
        }
        Network.networkGet(url!, parameters:parameters) { (json) in
            if json["code"] as! Int == 1 {
                if self.type == SongListsType.Search {
                    self.lists.removeAllObjects()
                }
                let array:NSArray = json["data"] as! NSArray
                for dic in array {
                    let song:songModel = songModel.init(dic: dic as? [String : AnyObject])
                    self.lists.addObject(song)
                }
                if self.parameters != nil  {
                    if array.count > 0 {
                        self.tableView?.mj_footer.endRefreshing()
                    } else {
                        self.tableView?.mj_footer.endRefreshingWithNoMoreData()
                    }
                }
            } else {
                if self.parameters != nil {
                    self.tableView?.mj_footer.endRefreshing()
                }
            }
            if (self.tableView != nil) {
                self.tableView?.reloadData()
            } else {
                self.initView()
            }
        }
    }
    
    func initView() {
        self.tableView = SMBTableView.init(frame: CGRectMake(0, 0, CGRect.screenWidth(), CGRect.screenHeight() - 64), style: UITableViewStyle.Plain)
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        self.tableView?.separatorStyle = UITableViewCellSeparatorStyle.None
        self.view.addSubview(self.tableView!)
        self.tableView?.registerClass(SongsTableViewCell.self, forCellReuseIdentifier: "cell")
        self.activityView = UIActivityIndicatorView.init(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        self.activityView?.center = self.view.center
        self.view.addSubview(self.activityView!)
        if self.parameters != nil {
            self.tableView?.mj_footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(self.footerRefresh))
        }
        if self.type == SongListsType.Search {
            self.searchBar = UISearchBar.init(frame: CGRectMake(50, 0, CGRect.screenWidth() - 100, 30))
            self.navigationItem.titleView = self.searchBar
            self.searchBar?.delegate = self
            self.searchBar?.placeholder = "歌名/歌手名"
            SMMusicPlayer.shareInstance().openClouse({ 
                self.searchBar?.resignFirstResponder()
                self.searchBar?.setShowsCancelButton(false, animated: true)
            })
            MusicList.shareInstance().openClouse({ 
                self.searchBar?.resignFirstResponder()
                self.searchBar?.setShowsCancelButton(false, animated: true)
            })
        }
    }
    
    
    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
        searchBar.setShowsCancelButton(true, animated: true)
        for view in (searchBar.subviews.last?.subviews)! {
            if view.isKindOfClass(UIButton) == true {
                let btn:UIButton = view as! UIButton
                btn.setTitle("取消", forState: UIControlState.Normal)
            }
        }
    }
    
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        searchBar.setShowsCancelButton(false, animated: true)
        if searchBar.text!.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 {
            self.network()
        }
        searchBar.resignFirstResponder()
    }
    
    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        searchBar.setShowsCancelButton(false, animated: true)
        searchBar.resignFirstResponder()
    }
    
    func footerRefresh() {
        page += 1
        self.parameters?.updateValue(page, forKey: "page")
        self.network()
    }
    
    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        if self.parameters == nil || self.type == SongListsType.Rank {
            return true
        }
        return false
    }
    
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        let db:Database = Database.init()
        let model:songModel = self.lists.objectAtIndex(indexPath.row) as! songModel
        if type == SongListsType.Download {
            db.delete(model, type: DBType.Download)
        } else {
            db.delete(model, type: DBType.Collect)
        }
        self.lists.removeObjectAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
        tableView.reloadData()
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:SongsTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! SongsTableViewCell
        cell.model = self.lists[indexPath.row] as! songModel
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let model:songModel = self.lists[indexPath.row] as! songModel
        SMMusicPlayer.shareInstance().play(model)
        MusicList.shareInstance().currentNumberOfSongs = indexPath.row
        MusicList.shareInstance().reloadLists(self.lists)
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 50
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.lists.count
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
